package com.can.Lock;

import java.util.concurrent.locks.ReentrantLock;

//测试Lock锁
//显式的定义加锁
public class TestLock {

    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();

        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }

}

class TestLock2 implements Runnable{

    private int ticketNums = 10; //票数
    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){

            try {
                //加锁
                lock.lock();
                if(ticketNums>0){
                    //模拟延时，放大并发问题
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //取票
                    System.out.println(ticketNums--);
                }else{
                    //没票return
                    return;
                }
            }finally {
                //解锁
                lock.unlock();
            }


        }
    }
}
